package com.ybkj.o2o.mc.controller.res;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ybkj.o2o.mc.common.DataGrid;
import com.ybkj.o2o.mc.common.query.DepartmentQuery;
import com.ybkj.o2o.mc.common.transport.Error;
import com.ybkj.o2o.mc.common.transport.Result;
import com.ybkj.o2o.mc.entity.Department;
import com.ybkj.o2o.mc.entity.Enterprise;
import com.ybkj.o2o.mc.entity.PassengerAccount;
import com.ybkj.o2o.mc.entity.PassengerGrade;
import com.ybkj.o2o.mc.entity.PassengerManage;
import com.ybkj.o2o.mc.manager.DepartmentManager;
import com.ybkj.o2o.mc.manager.EnterpriseManager;
import com.ybkj.o2o.mc.manager.PassengerManageManager;
import com.ybkj.o2o.mc.manager.PassengerManager;
import com.google.common.base.Preconditions;

/**
 * 
 * @author Yuan Tianyang.---2017/6/30
 *
 */
@RestController
@RequestMapping(value = "api/departments")
public class DepartmentRes {
	
	@Autowired
	private DepartmentManager departmentManager;
	
	@Autowired
	private PassengerManager passengerManager;
	
	@Autowired
	private PassengerManageManager passengerManageManager;
	
	@Autowired
	private EnterpriseManager enterpriseManager;

	/**
	 * 新增部门
	 * 
	 * @param name
	 * @param companyId
	 * @param companyName
	 * @param enterpriseId
	 * @param enterpriseName
	 * @param remark
	 * @param appKey
	 * @return
	 */
	@Transactional(rollbackFor=Exception.class)
	@RequestMapping(value = {"", "/"}, method = RequestMethod.POST)
	public ResponseEntity<Object> create (
			@RequestParam(value="name")String name,
			@RequestParam(value="companyId")Long companyId,
			@RequestParam(value="companyName")String companyName,
			@RequestParam(required = false,value="enterpriseId")Long enterpriseId,
			@RequestParam(required = false,value="enterpriseName")String enterpriseName,
			@RequestParam(required = false,value="parentId")Long parentId,
			@RequestParam(required = false,value="parentName")String parentName,
            @RequestParam(required = false, value = "manageAccount") String manageAccount,
            @RequestParam(required = false, value = "managePassword") String managePassword,
			@RequestParam(required = false,value="remark")String remark,
			@RequestParam(value="appKey") String appKey){
		ResponseEntity<Object> responseEntity = null;

		name = StringUtils.trimToEmpty(name);
	    appKey = StringUtils.trimToEmpty(appKey);

	    Preconditions.checkArgument(StringUtils.isNotBlank(name), "部门名称不能为空");
	    Preconditions.checkArgument(companyId != null && companyId != 0, "所属公司不能为空");
	    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
	    
	    //验证部门是否已经存在
	    Department department = departmentManager.exists(name, appKey, enterpriseId);
	    
	    if( null != department ){
	    	Result<Department> result = new Result<>(-6, "该企业已存在此部门", null);

		    responseEntity = new ResponseEntity<>(result, HttpStatus.UNPROCESSABLE_ENTITY);
	
		    return responseEntity;
	    }
	    
	    //保存企业信息
	    try {
	      department = new Department();
	      department.setName(name);
	      department.setCompanyId(companyId);
	      department.setCompanyName(companyName);
	      department.setEnterpriseId(enterpriseId);
	      department.setEnterpriseName(enterpriseName);
	      department.setParentId(parentId);
	      department.setParentName(parentName);
	      department.setAppKey(appKey);

	      if(remark == null || remark.length() < 150){
	    	  department.setRemark(remark);
	      }else {
	    	  Result<Department> result = new Result<>(-6, "备注长度最大150个字符串", null);

		      responseEntity = new ResponseEntity<>(result, HttpStatus.UNPROCESSABLE_ENTITY);

		      return responseEntity;
	      }
	      
	      department = departmentManager.insert(department);

	      //添加部门管理员
	      if( null != department && null != manageAccount){
	    	  PassengerManage passengerManage = new PassengerManage();
	    	  passengerManage.setManageAccount(manageAccount);
	    	  PassengerManage passengerManageNew = passengerManageManager.findPassengerManagerByParam(passengerManage);
	    	  if (null != passengerManageNew) {
	    		  departmentManager.deleteByPrimaryKey(department.getId(), appKey);
	    		  Result<Department> result = new Result<>(-2, "已存在相同名称的部门管理员", null);

	    	      responseEntity = new ResponseEntity<>(result, HttpStatus.NOT_IMPLEMENTED);

	    	      return responseEntity;
	    	  }
	    	  passengerManage.setDepartmentId(department.getId());
	    	  passengerManage.setDepartmentName(department.getName());
	    	  passengerManage.setEnterpriseId(department.getEnterpriseId());
	    	  passengerManage.setEnterpriseName(department.getEnterpriseName());
	    	  passengerManage.setManagePassword(managePassword);
	    	  passengerManage.setManageGrade(1);
	    	  passengerManage.setAppKey(appKey);
	    	  
	    	  passengerManage = passengerManageManager.insert(passengerManage);
	    	  
	      }
	      
	      Result<Department> result = new Result<>(0, "成功", department);

	      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

	      return responseEntity;

	    } catch (Exception ex) {

	      ex.printStackTrace();
	      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

	      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

	      return responseEntity;
	    }
		
	}
	
	/**
	 * 通过id和appKey查询部门
	 * 
	 * @param id
	 * @param appKey
	 * @return
	 */
	@RequestMapping(value="{id}",method = RequestMethod.GET)
	public ResponseEntity<Object> findOneDepartment(
			@PathVariable("id") Long id,
			@RequestParam("appKey") String appKey){
		
		ResponseEntity<Object> responseEntity = null;

	    appKey = StringUtils.trimToEmpty(appKey);
		
		try {

			Department department = departmentManager.findByIdAndAppKey(id,appKey);

			Result<Department> result = new Result<>(0, "成功", department);

			responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

			return responseEntity;

		} catch (Exception ex) {

			ex.printStackTrace();
			Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

			responseEntity = new ResponseEntity<>(error,
					HttpStatus.INTERNAL_SERVER_ERROR);

			return responseEntity;
		}
	}
	
	/**
	 * 分页查询部门
	 */
	@RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
	public ResponseEntity<Object> findByParam(
			@RequestParam(required = false, value = "companyId")Long companyId,
			@RequestParam(required = false, value = "name")String name,
			@RequestParam(required = false, value = "start")Long start,
			@RequestParam(required = false, value = "end")Long end,
			@RequestParam("page") Integer page,
			@RequestParam("rows") Integer rows,
         	@RequestParam("appKey") String appKey){
		
		ResponseEntity<Object> responseEntity = null;
		
		appKey = StringUtils.trimToEmpty(appKey);
	    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
	    
	    DepartmentQuery departmentQuery = new DepartmentQuery();
	    
	    departmentQuery.setAppKey(appKey);
	    departmentQuery.setCompanyId(companyId);
	    departmentQuery.setName(name);
	    departmentQuery.setStartTime(start);
	    departmentQuery.setEndTime(end);
	    departmentQuery.setPage(page);
	    departmentQuery.setRows(rows);
	    
		return getDepartmentForPage(departmentQuery);
	}
	
  /**
   * 后台查询企业信息.
   */
  @RequestMapping(value = "listData", method = RequestMethod.GET)
  public ResponseEntity<Object> listData(
		  	@RequestParam(required = false, value = "companyId")Long companyId,
		  	@RequestParam(required = false, value = "enterpriseId")Long enterpriseId,
			@RequestParam(required = false, value = "name") String name,
			@RequestParam(required = false, value = "start") Long start,
			@RequestParam(required = false, value = "end") Long end,
			@RequestParam(required = false, value = "page") Integer page,
			@RequestParam(required = false, value = "rows") Integer rows,
			@RequestParam(required = false, value = "appKey") String appKey) {

	  	ResponseEntity<Object> responseEntity = null;
	  
	  	appKey = StringUtils.trimToEmpty(appKey);
	    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
	    
	    DepartmentQuery departmentQuery = new DepartmentQuery();
	    
	    departmentQuery.setAppKey(appKey);
	    departmentQuery.setCompanyId(companyId);
	    departmentQuery.setEnterpriseId(enterpriseId);
	    departmentQuery.setName(name);
	    departmentQuery.setStartTime(start);
	    departmentQuery.setEndTime(end);
	    departmentQuery.setPage(page);
	    departmentQuery.setRows(rows);
	    
		return getDepartmentForPage(departmentQuery);
  }
	
  
	/**
	 * 提供查询数据封装功能
	 * 
	 * @param departmentQuery
	 * @return
	 */
	private ResponseEntity<Object> getDepartmentForPage(DepartmentQuery departmentQuery) {

	    ResponseEntity<Object> responseEntity = null;
	
	    try {
	    	
	      DataGrid<Department> dataGrid = departmentManager.findByDepartmentQuery(departmentQuery);
	
	      Result<DataGrid<Department>> result = new Result<>(0, "成功", dataGrid);
	
	      responseEntity = new ResponseEntity<>(result, HttpStatus.OK);
	
	      return responseEntity;
	
	    } catch (Exception ex) {
	
	      ex.printStackTrace();
	      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
	
	      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
	
	      return responseEntity;
	    }
	  }
	
	/**
	 * 修改部门信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.POST)
	public ResponseEntity<Object> update(
			@PathVariable("id") Long id,
			@RequestParam(required = false,value = "name") String name,
			@RequestParam(required = false,value = "remark") String remark,
			@RequestParam(required = false,value = "parentId")Long parentId,
			@RequestParam(required = false,value = "parentName")String parentName,
	        @RequestParam(required = false,value = "manageAccount") String manageAccount,
	        @RequestParam(required = false,value = "managePassword") String managePassword,
			@RequestParam("appKey") String appKey){
		
		ResponseEntity<Object> responseEntity = null;

	    name = StringUtils.trimToEmpty(name);
	    appKey = StringUtils.trimToEmpty(appKey);
		
		Preconditions.checkArgument(id != null && id != 0, "部门id不能为空");
	    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

	    //验证企业信息是否已经存在
	    Department department = departmentManager.exists(name, appKey, departmentManager.findByIdAndAppKey(id, appKey).getEnterpriseId());
	    
	    //有名字查询的部门     id与传入
	    
	    if(null != department){
	    	if(!department.getId().equals(id) && department.getName().equals(name)){
	    		Result<Department> result = new Result<>(-1, "当前企业下该部门已存在",department);
	    		responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);
	    		return responseEntity;
	    	}
	    }
		// 修改部门信息
		try {
			department = departmentManager.findByIdAndAppKey(id, appKey);
			department.setName(name);
			
			try {
				Department parentDepartment = new Department();
				Long parentDepartmentId = parentId;
				Long departmentId = id;
				//储存循环中的Id
				List<Long> ids = new ArrayList<Long>();
				//对父部门进行递归查询，将查询到的ID存储到ids中，如果pId在ids中则造成逻辑错误,抛出存在异常
				while ( null!= parentDepartmentId) {
					ids.add(departmentId);
					parentDepartment = departmentManager.findByIdAndAppKey(parentDepartmentId, appKey);
					departmentId = parentDepartment.getId();
					parentDepartmentId = parentDepartment.getParentId();
					
					if(null != parentDepartmentId && ids.contains(parentDepartmentId) ){
						Result<Department> result = new Result<>(-6, "当前部门在所选部门的父部门中", null);
						
				        responseEntity = new ResponseEntity<>(result, HttpStatus.UNPROCESSABLE_ENTITY);
		
				        return responseEntity;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			department.setParentId(parentId);
			department.setParentName(parentName);
			if(remark == null || remark.length() < 150){
		    	  department.setRemark(remark);
		      }else {
		    	  Result<Department> result = new Result<>(-6, "备注长度最大150个字符串", null);
	
			      responseEntity = new ResponseEntity<>(result, HttpStatus.UNPROCESSABLE_ENTITY);
	
			      return responseEntity;
		      }
			PassengerManage passengerManage = new PassengerManage();
			passengerManage.setAppKey(appKey);
			passengerManage.setDepartmentId(id);
			PassengerManage passengerManageNew = passengerManageManager.findPassengerManagerByParam(passengerManage);
			passengerManage.setDepartmentName(name);
			passengerManage.setManageAccount(manageAccount);

			PassengerManage passengerManageByAccount = new PassengerManage();
			PassengerManage passengerManageByParam = null;
			if(null != manageAccount){	
				passengerManageByAccount.setManageAccount(manageAccount);
				passengerManageByParam = passengerManageManager
						.findPassengerManagerByParam(passengerManageByAccount);
			}
			
			if( null != passengerManageNew){
				if( null != manageAccount){
					if (!passengerManageNew.getManageAccount().equals(manageAccount)
							&& null != passengerManageByParam) {
						Result<Department> result = new Result<>(-2, "已存在相同名称的部门管理员", null);
						
						responseEntity = new ResponseEntity<>(result,
								HttpStatus.NOT_IMPLEMENTED);
						
						return responseEntity;
					}
				}else {
					passengerManageManager.deleteByParam(passengerManageNew);
				}
			}else {
				if(null == passengerManageByParam){
					if(null !=manageAccount && null== managePassword){
						Result<Department> result = new Result<>(-2, "请为新增管理员设置密码", null);
						
						responseEntity = new ResponseEntity<>(result,
								HttpStatus.NOT_IMPLEMENTED);
						
						return responseEntity;
					}
					
					if (null != manageAccount && null != managePassword) {
						Enterprise enterpriseByDepartmentId = enterpriseManager.findOne(departmentManager.findByIdAndAppKey(id, appKey).getEnterpriseId(), appKey);
						passengerManage.setEnterpriseId(enterpriseByDepartmentId.getId());
						passengerManage.setEnterpriseName(enterpriseByDepartmentId.getName());
						passengerManage.setManageGrade(1);
						passengerManageManager.insert(passengerManage);
					}
					
				}else {
					Result<Department> result = new Result<>(-2, "已存在相同名称的部门管理员", null);

					responseEntity = new ResponseEntity<>(result,
							HttpStatus.NOT_IMPLEMENTED);

					return responseEntity;
				}
			}
			
		    if( null!=managePassword ){
		    	passengerManage.setManagePassword(managePassword);
		    }
		    passengerManage.setAppKey(appKey);
		    
		    
		    departmentManager.updateByPrimaryKey(department);
		    passengerManager.updateDepartmentName(department.getId(),department.getName(),appKey);
		    passengerManageManager.update(passengerManage);

		    Result<Department> result = new Result<>(0, "成功", null);
			
			responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

			return responseEntity;

		} catch (Exception ex) {

			ex.printStackTrace();
			Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

			responseEntity = new ResponseEntity<>(error,
					HttpStatus.INTERNAL_SERVER_ERROR);

			return responseEntity;
		}
	    
			
	}
	
	  /**
	   * 删除部门.
	   */
	  @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
	  public ResponseEntity<Object> delete(@PathVariable("id") Long id,
	                                       @RequestParam("appKey") String appKey) {
	    ResponseEntity<Object> responseEntity = null;

	    appKey = StringUtils.trimToEmpty(appKey);

	    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

	    //验证部门信息是否已经存在
	    Department department = departmentManager.findByIdAndAppKey(id, appKey);

	    Preconditions.checkArgument(department != null, "部门不存在");

	    try {
	      
	      deleteDepartmentsById(id,appKey);
	      
	      PassengerManage passengerManage = new PassengerManage();
	      passengerManage.setDepartmentId(id);
	      passengerManageManager.deleteByParam(passengerManage);
	      departmentManager.deleteByPrimaryKey(id, appKey);
	      passengerManager.updateByDelDepartment(id,appKey);
	      
	      Result<PassengerGrade> result = new Result<>(0, "成功", null);

	      responseEntity = new ResponseEntity<>(result, HttpStatus.NO_CONTENT);

	      return responseEntity;

	    } catch (Exception ex) {

	      ex.printStackTrace();
	      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
	      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
	      return responseEntity;
	    }	
	  }
	  
	  public void deleteDepartmentsById(Long id,String appKey){
		  DepartmentQuery departmentQuery = new DepartmentQuery();
		  departmentQuery.setParentId(id);
		  
		  DataGrid<Department> dataGrid = departmentManager.findByDepartmentQuery(departmentQuery);
		  
		  PassengerManage passengerManage = new PassengerManage();
		  
	      List<Department> departmentRows = dataGrid.getRows();
	      if (!departmentRows.isEmpty()) {
			for (Department departmentRow : departmentRows) {
				departmentManager.deleteByPrimaryKey(departmentRow.getId(), appKey);
				passengerManager.updateByDelDepartment(departmentRow.getId(),appKey);
				passengerManage.setDepartmentId(departmentRow.getId());
				passengerManageManager.deleteByParam(passengerManage);
				deleteDepartmentsById(departmentRow.getId(),appKey);
			}
		}
	  }
	  
	  /**
	   * 部门充值.
	   */
	  @RequestMapping(value = "{departmentId}/departmentAccountDetail", method = RequestMethod.POST)
	  public ResponseEntity<Object> createAccount(
	          @PathVariable("departmentId") Long departmentId,
	          @RequestParam(required = false, value = "departmentName") String departmentName,
	          @RequestParam("money") Double money,
	          @RequestParam("payType") String payType,
	          @RequestParam("operator") String operator,
	          @RequestParam("updateBlance") Boolean updateBlance,
	          @RequestParam(required = false, value = "useNoDrawMoney") Boolean useNoDrawMoney,
	          @RequestParam(required = false, value = "details") String details,
	          @RequestParam(required = false, value = "tradeNo") String tradeNo,
	          @RequestParam(required = false, value = "orderNo") String orderNo,
	          @RequestParam(required = false, value = "passenger_id") Long passenger_id,
	          @RequestParam(required = false, value = "passenger_phone") String passenger_phone,
	          @RequestParam(required = false, value = "passenger_name") String passenger_name,
	          @RequestParam(required = false, value = "orderId") Long orderId,
	          @RequestParam(required = false, value = "orderType") Integer orderType,
	          @RequestParam("appKey") String appKey) {
	    ResponseEntity<Object> responseEntity = null;

	    appKey = StringUtils.trimToEmpty(appKey);
	    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
	    Preconditions.checkArgument(StringUtils.isNotBlank(payType), "支付类型不能为空");
	    Preconditions.checkArgument(StringUtils.isNotBlank(operator), "操作人不能为空");
	    Department department= departmentManager.findByIdAndAppKey(departmentId, appKey);
	    
	    Preconditions.checkArgument(department != null, "部门不存在");

	    try {

	      updateBlance = BooleanUtils.toBoolean(updateBlance);
	      useNoDrawMoney = BooleanUtils.toBoolean(useNoDrawMoney);

	      PassengerAccount account = new PassengerAccount();
	      account.setEnterpriseId(department.getEnterpriseId());
	      account.setEnterpriseName(department.getEnterpriseName());
	      account.setDepartmentId(departmentId);
	      account.setDepartmentName(departmentName);
	      account.setDepartmentName(department.getName());
	      account.setMoney(money);
	      account.setOrderNo(orderNo);
	      account.setOrderId(orderId);
	      account.setOrderType(orderType);
	      account.setPassengerId(passenger_id);
	      account.setPassengerName(passenger_name);
	      account.setPassengerPhone(passenger_phone);
	      account.setDetails(details);
	      account.setTradeNo(tradeNo);
	      account.setPayType(payType);
	      account.setOperator(operator);
	      account.setAppKey(appKey);
	      account.setCompanyId(department.getCompanyId());
	      
	      account = departmentManager.updateAccount(department, account, updateBlance, useNoDrawMoney);
	      
	      Result<PassengerAccount> result = new Result<>(0, "成功", account);
	      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

	      return responseEntity;
	    } catch (Exception ex) {

	      ex.printStackTrace();
	      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

	      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

	      return responseEntity;
	    }
	  }
	  
}
